package com.example.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ai.entity.InterviewAnswer;
import com.example.ai.entity.InterviewScore;
import com.example.ai.mapper.AiInterviewAnswerMapper;
import com.example.ai.mapper.InterviewScoreMapper;
import com.example.ai.service.InterviewScoreService;
import com.example.ai.util.AIScoreUtil;
import com.example.ai.vo.InterviewScoreVO;
import com.example.mianshiguan.api.InterviewerConfigService;
import com.example.mianshiguan.api.dto.InterviewerConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 面试评分服务实现类
 */
@Slf4j
@Service
public class InterviewScoreServiceImpl implements InterviewScoreService {

    @Autowired
    private InterviewScoreMapper scoreMapper;

    @Autowired
    private AiInterviewAnswerMapper interviewAnswerMapper;

    @Autowired
    private InterviewerConfigService interviewerConfigService;

    @Autowired
    private AIScoreUtil aiScoreUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InterviewScoreVO generateScore(Integer candidateId) {
        try {
            log.info("开始生成评分，候选人ID: {}", candidateId);
            
            // 1. 获取面试官配置
            InterviewerConfigDTO config = interviewerConfigService.getConfig(candidateId);
            if (config == null) {
                log.error("未找到面试官配置，candidateId: {}", candidateId);
                return null;
            }

            // 2. 获取候选人的所有答案
            String answers = getCandidateAnswers(candidateId);
            if (answers == null || answers.isEmpty()) {
                log.error("未找到候选人答案，candidateId: {}", candidateId);
                return null;
            }

            // 3. 调用AI进行评分(最多重试3次)
            InterviewScoreVO scoreVO = null;
            int retryCount = 0;
            while (retryCount < 3 && scoreVO == null) {
                try {
                    scoreVO = aiScoreUtil.calculateScore(answers, config);
                    if (scoreVO != null) {
                        break;
                    }
                } catch (Exception e) {
                    log.error("AI评分失败，重试次数: {}", retryCount + 1, e);
                    retryCount++;
                    if (retryCount < 3) {
                        Thread.sleep(1000); // 等待1秒后重试
                    }
                }
            }

            if (scoreVO == null) {
                log.error("AI评分失败，已达到最大重试次数");
                return null;
            }

            // 4. 保存评分结果
            saveScore(candidateId, scoreVO);
            log.info("评分保存成功");

            return scoreVO;
        } catch (Exception e) {
            log.error("生成评分失败", e);
            return null;
        }
    }

    @Override
    public InterviewScoreVO getScore(Integer candidateId) {
        try {
            log.info("开始获取评分，候选人ID: {}", candidateId);
            
            // 1. 查询最新评分记录
            LambdaQueryWrapper<InterviewScore> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InterviewScore::getCandidateId, candidateId)
                   .orderByDesc(InterviewScore::getCreateTime)
                   .last("LIMIT 1");
            
            InterviewScore score = scoreMapper.selectOne(wrapper);
            
            // 2. 如果没有评分记录，尝试生成新的评分
            if (score == null) {
                log.info("未找到评分记录，尝试生成新的评分");
                return generateScore(candidateId);
            }
            
            // 3. 转换并返回评分结果
            InterviewScoreVO scoreVO = new InterviewScoreVO();
            BeanUtils.copyProperties(score, scoreVO);
            return scoreVO;
            
        } catch (Exception e) {
            log.error("获取评分记录失败", e);
            return null;
        }
    }

    /**
     * 获取候选人的所有答案
     */
    private String getCandidateAnswers(Integer candidateId) {
        List<InterviewAnswer> answers = interviewAnswerMapper.selectByCandidateId(candidateId);
        if (answers == null || answers.isEmpty()) {
            return null;
        }
        
        return answers.stream()
                .map(InterviewAnswer::getAnswer)
                .collect(Collectors.joining("\n"));
    }

    /**
     * 保存评分结果
     */
    private void saveScore(Integer candidateId, InterviewScoreVO scoreVO) {
        InterviewScore score = new InterviewScore();
        score.setCandidateId(candidateId);
        score.setTechnicalScore(scoreVO.getTechnicalScore());
        score.setCommunicationScore(scoreVO.getCommunicationScore());
        score.setProblemSolvingScore(scoreVO.getProblemSolvingScore());
        score.setTotalScore(scoreVO.getTotalScore());
        score.setStrengths(scoreVO.getStrengths());
        score.setSuggestions(scoreVO.getSuggestions());
        
        LocalDateTime now = LocalDateTime.now();
        score.setCreateTime(now);
        score.setUpdateTime(now);
        
        scoreMapper.insert(score);
    }
} 